package com.t.bricks.bussiness.service.rechargecard.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.t.bricks.bussiness.db.dao.rechargecard.RechargeCardDao;
import com.t.bricks.bussiness.db.entity.rechargecard.RechargeCard;
import com.t.bricks.bussiness.db.entity.rechargecard.base.CustomerAccountBase;
import com.t.bricks.bussiness.db.entity.rechargecard.base.RechargeBase;
import com.t.bricks.bussiness.model.rechargecard.AddInfo;
import com.t.bricks.bussiness.model.rechargecard.ConditionRechargeCard;
import com.t.bricks.bussiness.service.rechargecard.RechargeCardService;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.model.OrderInfoList;
import com.t.bricks.model.Page;
import com.t.bricks.utils.function.data.MoneyUtil;
import com.t.bricks.utils.function.data.UUIDUtil;
import com.t.bricks.utils.function.json.JacksonShell;
import com.t.bricks.utils.spring.ModuleUtil;

/**
 * 充值卡'RechargeCard表'基本业务操作类接口实现
 */
@Service
public class RechargeCardServiceImpl implements RechargeCardService {

	@Autowired
	private RechargeCardDao rechargeCardDao;
	
	/**
	 * 创建sRecordKey用的干扰串
	 */
	@Value("${app.record.key.jam:123456}")
	private String recordKeyJam;

	/**
	 * 批量添加
	 * @param addInfo 批量添加信息实体
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity adds(AddInfo addInfo) {
		if (null == addInfo) {
			return MsgEmity.err(8011, "批量添加信息实体不能为空");
		}
		
		if (null == addInfo.getiSize() || addInfo.getiSize().intValue() < 1) {
			return MsgEmity.err(8201, "添加数量必须大于0");
		}
		
		RechargeCard rechargeCard = JacksonShell.toJavaObject(addInfo, RechargeCard.class);
		if (null == rechargeCard) {
			return MsgEmity.err(8202, "对象转换失败");
		}

		rechargeCard.setuId("随便");//随便设置一个值
		rechargeCard.setsNo("随便");//随便设置一个值
		rechargeCard.setdActiv(null);//激活时间必须清理
		rechargeCard.setsCustomerId(null);//所属顾客账号必须清理
		
		MsgEmity me = ModuleUtil.validDbEntityByAdd(rechargeCard);// 通用的基本数据验证,如果要进行比较复杂的数据验证则可以屏蔽掉此方法自行编写
		if (!me.isSuccess()) {
			return me;
		}
		
		if (!MoneyUtil.isPlus(rechargeCard.getmPrice())) {
			return MsgEmity.err(8203, "金额必须是正数");
		}
		
		if (rechargeCard.getdStartDate().after(rechargeCard.getdEndDate())) {
			return MsgEmity.err(8204, "'开始时间'必须小于'过期时间'");
		}
		
		me = ModuleUtil.supplyDbEntityAttrByAdd(rechargeCard, "随便", null);// 补充数据,如添加id、当前用户、当前时间等
		if (!me.isSuccess()) {
			return me;
		}
		
		List<RechargeCard> list = new ArrayList<>(addInfo.getiSize());
		for (int i = 0; i < addInfo.getiSize(); i++) {
			RechargeCard obj = rechargeCard.clone();
			obj.setuId(UUIDUtil.get());
			obj.setsNo(UUIDUtil.get());
			obj.setsPass(UUIDUtil.get());
			
			list.add(obj);
		}
		
		return rechargeCardDao.adds(list);
	}

	/**
	 * 删除
	 * @param iVersion 数据版本号
	 * @param uId 记录编号
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity del(Integer iVersion, String uId) {
		if (null == uId || "".equals(uId.trim())) {
			return new MsgEmity(false, "信息编号参数错误，请刷新重试！", 8001);
		}
		
		if (null == iVersion || iVersion.intValue() < 1) {
			return new MsgEmity(false, "信息版本参数错误，其值应大于0！", 8002);
		}

		return rechargeCardDao.del(uId, iVersion);
	}
	
	/**
	 * 查询分页
	 * @param page 分页信息对象
	 * @param orders 排序数据集合
	 * @param sLikeStr 全文检索
	 * @param condition 查询条件对象
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByPage(Page page, OrderInfoList orders, String sLikeStr,
			ConditionRechargeCard condition) {
		if (null == page) {
			page = new Page(new ArrayList<RechargeCard>());
		}

		return rechargeCardDao.findByPage(page, orders, sLikeStr, condition);
	}

	/**
	 * 根据记录编号查询符合分页数据的某条记录
	 * @param uId
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByPageRow(String uId) {
		if (null == uId || "".equals(uId.trim())) {
			return new MsgEmity(false, "编号不能为空！", 8001);
		}
		
		return rechargeCardDao.findByPageRow(uId);
	}

	/**
	 * 创建Excel文件内容
	 * @param orders 排序数据集合
	 * @param sLikeStr 全文检索
	 * @param condition 查询条件对象
	 * @return MsgEmity 返回结构中data为创建的经过压缩的Excel内容,接收端需要进行解压,msg为文件名
	 */
	@Override
	public MsgEmity export(OrderInfoList orders, String sLikeStr, ConditionRechargeCard condition) {
		MsgEmity me = rechargeCardDao.findByExport(orders, sLikeStr, condition);//查询数据
		if(!me.isSuccess()) {
			return me;
		}
		
		return ModuleUtil.crateExcel(me.getData(), "充值卡.xls");//根据Excel的xml模板创建文件内容
	}
	
	//----------------------------- 自动生成代码结束 ---------------------------//

	/**
	 * 按编号占用
	 * @param sNo 号码
	 * @param sPass 激活码
	 * @return
	 */
	@Override
	public MsgEmity active(String sNo, String sPass) {
		if (null == sNo || "".equals(sNo.trim())) {
			return new MsgEmity(false, "信息编号不能为空！", 8001);
		}
		
		if (null == sPass || "".equals(sPass.trim())) {
			return new MsgEmity(false, "激活码不能为空！", 8002);
		}
		
		MsgEmity me = rechargeCardDao.findByNo(sNo);
		if (!me.isSuccess()) {
			return me;
		}
		
		RechargeCard rechargeCard = me.getData();
		
		if (!sPass.trim().equals(rechargeCard.getsPass())) {
			return new MsgEmity(false, "激活码错误！", 8003);
		}
		
		if (rechargeCard.getiState().intValue() != 1) {
			return new MsgEmity(false, "充值卡不是待领状态！", 8004);
		}
		
		if (null != rechargeCard.getsCustomerId()) {
			return new MsgEmity(false, "充值卡已被领取！", 8005);
		}
		
		if (rechargeCard.getsRecordKey().equals(rechargeCard.createRecordKey(recordKeyJam))) {
			return new MsgEmity(false, "充值卡验证密钥错误！", 8006);
		}
		
		String sCustomerId = ModuleUtil.currentLoginUserId();
		Date now = new Date();
		
		rechargeCard.setdActiv(now);
		rechargeCard.setsCustomerId(sCustomerId);
		rechargeCard.setsModifieder(sCustomerId);
		rechargeCard.setdModifiedDate(now);
		rechargeCard.setiState(2);
		rechargeCard.setiVersion(rechargeCard.getiVersion());
		rechargeCard.setsRecordKey(rechargeCard.createRecordKey(recordKeyJam));

		return rechargeCardDao.employById(rechargeCard);
	}

	/**
	 * 充值卡充值
	 * 若想激活并充值则必须传入激活码
	 * @param sNo
	 * @param sPass 激活码
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity recharge(String sNo, String sPass) {
		if (null == sNo || "".equals(sNo.trim())) {
			return new MsgEmity(false, "信息编号不能为空！", 8001);
		}
		
		sNo = sNo.trim();
		
		MsgEmity me = rechargeCardDao.findByNo(sNo);
		if (!me.isSuccess()) {
			return me;
		}

		String sCustomerId = ModuleUtil.currentLoginUserId();
		
		RechargeCard rechargeCard = me.getData();
		
		if (!rechargeCard.getsNo().equals(sNo)) {
			return new MsgEmity(false, "号码不一致！", 8002);
		}
		
		if (!sCustomerId.equals(rechargeCard.getsCustomerId())) {
			return new MsgEmity(false, "账号不一致！", 8003);
		}
		
		if (rechargeCard.getiState().intValue() == 1) {//如果是待激活状态则必须
			if (null != sPass && !"".equals(sPass.trim())) {//如果传入了激活码,则可能想激活并充值
				return new MsgEmity(false, "激活码不能为空！", 8004);
			}

			if (!sPass.trim().equals(rechargeCard.getsPass())) {
				return new MsgEmity(false, "激活码错误！", 8005);
			}
			
			rechargeCard.setsCustomerId(sCustomerId);//赋予激活用户
		}
		
		if (rechargeCard.getiState().intValue() > 2) {
			return new MsgEmity(false, "充值卡状态必须是[待领或待用]！", 8006);
		}
		
		if (null != rechargeCard.getsCustomerId() && !sCustomerId.equals(rechargeCard.getsCustomerId())) {
			return new MsgEmity(false, "充值卡已被领取！", 8007);
		}
		
		if (rechargeCard.getsRecordKey().equals(rechargeCard.createRecordKey(recordKeyJam))) {
			return new MsgEmity(false, "充值卡验证密钥错误！", 8008);
		}
		
		me = rechargeCardDao.findCustomer(sCustomerId);
		if (!me.isSuccess()) {
			return new MsgEmity(false, "获取顾客账号信息错误！", 8009);
		}
		
		CustomerAccountBase customerAccount = me.getData();
		if (!customerAccount.createRecordKey(recordKeyJam).equals(customerAccount.getsRecordKey())) {
			return new MsgEmity(false, "顾客账号验证密钥错误！", 8010);//账号信息验证错误
		}
		
		Date now = new Date();
		
		if (rechargeCard.getiState().intValue() == 1) {
			rechargeCard.setdActiv(now);//刚被激活
		}
		rechargeCard.setsCustomerId(sCustomerId);
		rechargeCard.setsModifieder(sCustomerId);
		rechargeCard.setdModifiedDate(now);
		rechargeCard.setiState(3);//状态(枚举,1:待领;2:待用;3:已用;4:过期;5失效)
		rechargeCard.setiVersion(rechargeCard.getiVersion());
		rechargeCard.setsRecordKey(rechargeCard.createRecordKey(recordKeyJam));

		customerAccount.setmFund(MoneyUtil.addMoney(customerAccount.getmFund(), rechargeCard.getmPrice()));
		customerAccount.setdModifiedDate(now);
		customerAccount.setiVersion(customerAccount.getiVersion() +1);
		customerAccount.setsRecordKey(customerAccount.createRecordKey(recordKeyJam));

		RechargeBase recharge = new RechargeBase();
		recharge.setuId(UUIDUtil.get());//记录编号
		recharge.setsCustomerId(sCustomerId);//顾客编号
		recharge.setsOpenid("无");//微信公共号
		recharge.setsOrderNo(sNo);//订单号
		recharge.setsSpbillCreateIp(ModuleUtil.currentLoginUserIp());//下单IP
		recharge.setsBody("使用充值卡充值");//订单描述
		recharge.setmFund(rechargeCard.getmPrice());//价格(元)
		recharge.setiTally(0);//积分
		recharge.setsMemo("通过充值卡充值");//备注
		recharge.setdModifiedDate(now);
		recharge.setiVersion(recharge.getiVersion() +1);
		recharge.setiState(4);
		recharge.setiErrorCount(0);
		recharge.setsRecordKey(recharge.createRecordKey(recordKeyJam));
		
		return rechargeCardDao.changeCustomerAccount(rechargeCard, recharge, customerAccount);
	}
	
	/**
	 * 将过期数据更新状态
	 * @return
	 */
	@Override
	public MsgEmity expire() {
		MsgEmity me = rechargeCardDao.expireData();
		if (!me.isSuccess()) {
			return me;
		}
		
		List<RechargeCard> list = me.getData();
		for (RechargeCard rechargeCard : list) {
			rechargeCardDao.expire(rechargeCard);
		}
		
		return MsgEmity.success("执行完毕");
	}
	
	/**
	 * 查询当前顾客所持优惠卷
	 * @param iState
	 * @return MsgEmity List<Coupon>
	 */
	@Override
	public MsgEmity findByCustomer(Integer iState) {
		if (null != iState && iState.intValue() < 2) {
			return new MsgEmity(false, "状态参数应大于1！", 8001);
		}
		
		return rechargeCardDao.findByCustomer(iState, ModuleUtil.currentLoginUserId());
	}

}
